<?php

namespace app\forms\field;

use app\forms\Model;
use app\models\Field;
use yii\db\Exception;
use yii\web\HttpException;
use app\validators\PositiveInteger;

/**
 * 字段 禁用、启用
 */
class StatusForm extends Model
{
    public $id;

    public function rules()
    {
        return [
            ['id', PositiveInteger::class],
            ['id', 'required'],
            ['id', 'exist', 'targetClass' => Field::class]
        ];
    }

    /**
     * @param $param
     * @param $status
     * @throws HttpException
     */
    public static function status($param, $status)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $model = Field::findOne($form['id']);
            $model->status = $status;
            $model->save(false);
        } catch (Exception $e) {
            $form->serverError();
        }

        $form->deleteOk();
    }
}